package com.shkco.xbjcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.shkco.xbjcc.constants.MQConstants;
import com.shkco.xbjcc.domain.MessageSms;
import com.shkco.xbjcc.dto.CourseOnLineSendMessageDto;
import com.shkco.xbjcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import static com.shkco.xbjcc.constants.MQConstants.*;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "course-sms-consumer-group",
        topic = COURSE_MESSAGE_TOPIC,
        selectorExpression = COURSE_SMS_TAG
)
public class CourseSmsConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body == null || body.length == 0){
            return;
        }

        String str = new String(body, StandardCharsets.UTF_8);
        CourseOnLineSendMessageDto courseOnLineSendMessageDto = JSON.parseObject(str, CourseOnLineSendMessageDto.class);

        log.info("发送成功！");

        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(courseOnLineSendMessageDto.getTitle());
        messageSms.setContent(courseOnLineSendMessageDto.getContent());
        messageSms.setSendTime(new Date());
        courseOnLineSendMessageDto.getUserSendMessageDtos().forEach(e->{
            messageSms.setUserId(e.getUserId());
            messageSmsService.insert(messageSms);
        });
    }
}
